
// use first channel of 16 channels (started from zero)
#define LEDC_CHANNEL_0 0

// use 13 bit precission for LEDC timer
#define LEDC_TIMER_13_BIT 13

// use 5000 Hz as a LEDC base frequency
#define LEDC_BASE_FREQ 144

// fade LED PIN (replace with LED_BUILTIN constant for built-in LED)
#define LED_PIN 5

void led_init()
{
    ledcSetup(LEDC_CHANNEL_0, LEDC_BASE_FREQ, LEDC_TIMER_13_BIT);
    ledcAttachPin(LED_PIN, LEDC_CHANNEL_0);
    ledcAnalogWrite2(ledcur);
}
// Arduino like analogWrite
// value has to be between 0 and valueMax
void ledcAnalogWrite(uint8_t channel, uint32_t value, uint32_t valueMax = 255)
{
    // calculate duty, 8191 from 2 ^ 13 - 1
    uint32_t duty = (8191 / valueMax) * min(value, valueMax);

    // write duty to LEDC
    ledcWrite(channel, duty);
}

void ledcAnalogWrite2(uint32_t value)
{
    if (value > 100)
        value = 100;

    float va = value;
    float va1 = value * value * 0.8191;

    // calculate duty, 8191 from 2 ^ 13 - 1
    uint32_t duty = va1;

    // write duty to LEDC
    ledcWrite(LEDC_CHANNEL_0, duty);
}
void autoled()
{
    if (ledcur < ledset)
        ledcur++;
    else if (ledcur > ledset)
    {
        ledcur--;
    }
    ledcAnalogWrite2(ledcur);
}
